package com.taxshare.api.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.taxshare.api.view.dto.BlackSyncDTO;
import com.taxshare.api.view.dto.HumanResourcesDTO;
import com.taxshare.response.beans.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
/**
 * @author hjh
 * @date 2021/4/20
 * @Description:黑名单同步
 */
@Service
@Slf4j
public class BlackService {

    @Value("${black.appKey}")
    private String appKey;

    @Value("${black.secret}")
    private String secret;

    @Value("${black.url}")
    private String url;

    @Value("${humanResources.url}")
    private String humanResourcesUrl;

    @Autowired
    RestTemplate customRest;

    /**
     * 黑名单同步
     * @param blackSyncDTO
     * @return
     */
    public Response syncBlack(BlackSyncDTO blackSyncDTO) {
        HashMap<Object, String> proMap = new HashMap<>();
        proMap.put("appKey", appKey);
        proMap.put("province", blackSyncDTO.getProvince());
        Map<String, Object> params = new HashMap<>();
        params.put("appKey", appKey);
        params.put("content", proMap);
        try {
            params.put("token", sha256_HMAC(JSONObject.toJSONString(proMap), secret));
        } catch (Exception e) {
            return Response.error("API-003", "加密异常：" + e.getMessage());
        }
        ResponseEntity<Response> respEntity = customRest.postForEntity(url, params, Response.class);
        Response body = respEntity.getBody();
        return Response.success(body);
    }

    /**
     * 加密
     * @param message
     * @param secret
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static String sha256_HMAC(String message, String secret) throws NoSuchAlgorithmException, InvalidKeyException {
        String hash = null;
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
        hash = byteArrayToHexString(bytes);
        return hash;
    }

    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b 字节数组
     * @return 字符串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }


    /**
     * 获取人力资源信息
     *
     * @param humanResourcesDTO
     * @return
     */
    public Response getResources(HumanResourcesDTO humanResourcesDTO) {
        String xml = humanResourcesDTO.getXml();
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "text/xml; charset=utf-8");
//        headers.add("SOAPAction","http://tempuri.org/GetUserOrgPost2");
        HttpEntity entity = new HttpEntity<>(xml, headers);
        String res = restTemplate.postForObject(humanResourcesUrl, entity, String.class);
        log.error("人员管线接口同步数据response============"+ JSONUtil.toJsonStr(res));
        return Response.success(res);
    }
}
